/**     
* @Title: MyUserService.java   
* @Package me.security.example.security   
* @Description: TODO   
* @author xaoyaoyao
* @date 2017年8月23日 下午4:39:42
*/
package me.security.example.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import me.security.example.dao.PermissionDao;
import me.security.example.dao.UserDao;
import me.security.example.entity.Permission;
import me.security.example.entity.User;

/**
 * @ClassName: MyUserService
 * @Description: TODO
 * @author xaoyaoyao
 * @date 2017年8月23日 下午4:39:42
 * 
 */
@Service
public class MyUserService implements UserDetailsService {

	@Autowired
	UserDao userDao;

	@Autowired
	PermissionDao permissionDao;

	@Override
	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
		User user = userDao.getByUserName(userName);
		if (user != null) {
			List<Permission> permissions = permissionDao.getByUserId(user.getId());
			List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
			for (Permission permission : permissions) {
				if (permission != null && permission.getName() != null) {
					GrantedAuthority grantedAuthority = new MyGrantedAuthority(permission.getPermissionUrl(),
							permission.getMethod());
					grantedAuthorities.add(grantedAuthority);
				}
			}
			user.setGrantedAuthorities(grantedAuthorities);
			return user;
		} else {
			throw new UsernameNotFoundException("admin: " + userName + " do not exist!");
		}
	}

}
